package com.collect.common.eventbus.support;

import com.collect.common.config.PropertiesConfig;
import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author hky
 * @Description
 * @Date 2021/1/18
 */
public class BaseEventBusSupport {
    private static final Logger log = LoggerFactory.getLogger(BaseEventBusSupport.class);
    private static Executor executor;
    private static EventBus eventBus;
    private static AsyncEventBus asyncEventBus;

    public void initEventBus(String eventBusName) throws Exception {
        String poolSize="event-bus.executor.core-pool-size";
        String maxPoolSize="event-bus.executor.maximum-pool-size";
        String aliveTime="event-bus.executor.keep-alive-time";
        String queueSize="event-bus.executor.queue-size";
        executor = new ThreadPoolExecutor(
                PropertiesConfig.getInt(poolSize),
                PropertiesConfig.getInt(maxPoolSize),
                PropertiesConfig.getLong(aliveTime),
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>( PropertiesConfig.getInt(queueSize)));
        eventBus = new EventBus(eventBusName);
        asyncEventBus = new AsyncEventBus(eventBusName, executor);
    }


    public void destroy() throws Exception {
        log.info("EventBus executor shutdown...");
        ((ThreadPoolExecutor)executor).shutdownNow();
    }

    public void register(Object listener){
        eventBus.register(listener);
    }
    public void asyncRegister(Object listener){
        asyncEventBus.register(listener);
    }
    public void unregister(Object listener){
        eventBus.unregister(listener);
    }
    public void asyncUnRegister(Object listener){
        asyncEventBus.unregister(listener);
    }

    public void post(Object event){
        eventBus.post(event);
    }

    public void asyncPost(Object event){
        asyncEventBus.post(event);
    }
}
